package cc.liyinghao.service.impl;

import cc.liyinghao.config.DefaultIpPrefixConfig;
import cc.liyinghao.mapper.SysContactsMapper;
import cc.liyinghao.mapper.SysUserMapper;
import cc.liyinghao.common.pojo.SysUser;
import cc.liyinghao.security.util.SecurityUtil;
import cc.liyinghao.service.SearchService;
import cc.liyinghao.response.SearchUserByUserNameVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
@RequiredArgsConstructor
public class SearchServiceImpl implements SearchService {

    private final SysUserMapper sysUserMapper;
    private final SysContactsMapper sysContactsMapper;
    private final DefaultIpPrefixConfig defaultIpPrefixConfig;

    @Override
    public List<SearchUserByUserNameVo> searchUserByUserName(String username) {
        LambdaQueryWrapper<SysUser> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.like(SysUser::getUsername, username);
        List<SysUser> sysUserList = sysUserMapper.selectList(lambdaQueryWrapper);
        if (sysUserList != null) {
            List<SearchUserByUserNameVo> searchUserByUserNameVoList = new ArrayList<>();
            for (SysUser sysUser : sysUserList) {
                SearchUserByUserNameVo searchUserByUserNameVo = new SearchUserByUserNameVo();
                searchUserByUserNameVo.setId(sysUser.getId());
                searchUserByUserNameVo.setUsername(sysUser.getUsername());
                searchUserByUserNameVo.setHeadImgUrl(defaultIpPrefixConfig.getDefaultStaticIp() + sysUser.getHeadImgUrl());
                // 返回是不是已经是联系人了
                int isContact = sysContactsMapper.isContact(SecurityUtil.getCurrentUserId(), sysUser.getId());
                searchUserByUserNameVo.setIsContact(isContact);
                searchUserByUserNameVoList.add(searchUserByUserNameVo);
            }
            return searchUserByUserNameVoList;
        }
        return null;
    }
}
